package com.bdqn.business.quality.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.business.academic.dao.CurriculumMapper;
import com.bdqn.business.access.dao.UserRepository;
import com.bdqn.business.quality.dao.ClassesMapper;
import com.bdqn.entity.academic.Curriculum;
import com.bdqn.entity.access.User;
import com.bdqn.entity.quality.Classes;
import com.bdqn.response.PageResult;
import com.bdqn.response.Result;
import com.bdqn.response.ResultCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ClassesService {

    @Autowired
    private ClassesMapper classesMapper;

    @Autowired
    private CurriculumMapper curriculumMapper;

    @Autowired
    private UserRepository userRepository;

    public Result getClassesList(Map<String, Object> map) {
        Integer page = Integer.parseInt(map.get("page").toString());
        Integer size = Integer.parseInt(map.get("size").toString());

        IPage<Classes> iPage = new Page<>(page,size);

        QueryWrapper<Classes> queryWrapper = new QueryWrapper<>();

        queryWrapper.orderByDesc("create_time");

        IPage<Classes> result = classesMapper.selectPage(iPage, queryWrapper);


        List<Classes> list = result.getRecords();

        PageResult<Classes> pageResult = new PageResult<>(result.getTotal(),list);

        return new Result(ResultCode.SUCCESS,pageResult);
    }

    public Result saveClasses(Classes classes) {

        classes.setCurriculumName(curriculumMapper.selectById(classes.getCurriculumId()).getName());

        List<String> teacherNames = new ArrayList<>();

        this.handleData(classes.getJyId(),teacherNames);
        this.handleData(classes.getZjId(),teacherNames);
        this.handleData(classes.getBzrId(),teacherNames);

        classes.setTeachers(StringUtils.join(teacherNames,","));

        classes.setCreateTime(new Date());
        classes.setPersonNumber(0);
        classes.setInvalid("1");

        classesMapper.insert(classes);

        return Result.SUCCESS();
    }

    private void handleData(String teacherId,List<String> teacherNames){
        if(teacherId == null) teacherNames.add("-");
        else teacherNames.add(userRepository.findById(teacherId).get().getNickName());
    }
}
